import { queryCurrent, queryUserPermissions, updataUserInfo, setPassword } from '@/services/users';
import { setAuthority } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';
import { message } from 'antd';

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: null,
    userList: [],
    permissions: []
  },
  effects: {
    *fetchCurrent({ payload }, { call, put }) {
      const { code, message: msg, data } = yield call(queryCurrent, payload);
      if (code === '000000' && data) {
        yield put({
          type: 'saveCurrentUser',
          payload: data
        });
        const { realname = '查悦社保', phoneNumber = '' } = data;
        const NOTail = phoneNumber && phoneNumber.length > 4 ? phoneNumber.substr(phoneNumber.length - 4, 4) : '';
        yield put({
          type: 'global/changeWatermark',
          payload: {
            watermark_txt: `${realname} ${NOTail}`
          }
        });
      } else {
        message.error(msg);
      }
    },

    *fetchPermissions({ payload }, { call, put }) {
      const response = yield call(queryUserPermissions, payload);
      const { code } = response;
      if (code === '000000') {
        yield put({
          type: 'savePermissions',
          payload: response
        });
      }
      return response;
    },
    /**
     * @description  更新用户信息
     * @author songs
     * @date 2019-09-18
     * @param {*} { payload }
     * @param {*} { call, put }
     * @returns
     */
    *upUserInfo({ payload }, { call, put }) {
      const response = yield call(updataUserInfo, payload);
      yield put({
        type: 'saveCurrentUser',
        payload: response.data
      });
      const { nikeName = '查阅社保', phoneNumber = '' } = response.data;
      yield put({
        type: 'global/changeWatermark',
        payload: {
          watermark_txt: `${nikeName} ${phoneNumber.slice(-4)}`
        }
      });
      return response;
    },
    /**
     * @description 更新密码
     * @author songs
     * @date 2019-09-18
     * @param {*} { payload }
     * @param {*} { call, put }
     * @returns
     */
    *upPassword({ payload }, { call, put }) {
      const response = yield call(setPassword, payload);
      if (response) {
        yield put({
          type: 'login/logout'
        });
      }
      return response;
    }
  },
  reducers: {
    saveCurrentUser(state, { payload = {} }) {
      return { ...state, currentUser: { ...state.currentUser, ...payload } };
    },

    /**
     * @description 保存权限列表
     * @author songs
     * @date 2020-01-11
     * @param {*} state
     * @param {*} { payload = {} }
     * @returns
     */
    savePermissions(state, { payload = {} }) {
      const { data = [] } = payload;
      setAuthority(data);
      reloadAuthorized();
      return { ...state, permissions: data };
    }
  }
};
export default UserModel;
